package com.kou.backend.utils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import jakarta.servlet.http.HttpServletRequest;


/**
 * 获取请求信息工具类
 *
 * @author: Kou
 * @since: 2023/9/2 13:04
 */
public class FetchRequestInfoUtils {
    /**
     * 获取当前请求用户的浏览器名称+版本
     *
     * @param request 请求信息
     * @return 浏览器名称+版本
     */
    public static String browserName(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        UserAgent ua = UserAgent.parseUserAgentString(userAgent);
        Browser browser = ua.getBrowser();
        return browser.getName() + "-" + browser.getVersion(userAgent);
    }

    /**
     * 获取操作用户的操作系统名称
     *
     * @param request 请求信息
     * @return 用户的操作系统名称
     */
    public static String osName(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        UserAgent ua = UserAgent.parseUserAgentString(userAgent);
        OperatingSystem os = ua.getOperatingSystem();
        return os.getName();
    }

    private static final String[] IP_HEADERS = new String[]{
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA"
    };

    /**
     * 获取当前用户的ip地址
     *
     * @param request 请求信息
     * @return ip
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = null;
        for (String header : IP_HEADERS) {
            ip = request.getHeader(header);
            if (isValidIp(ip)) {
                break;
            }
        }

        if (!isValidIp(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip != null && ip.contains(",")) {
            String[] ips = ip.split(",");
            for (String candidate : ips) {
                String trimmed = candidate.trim();
                if (isValidIp(trimmed)) {
                    ip = trimmed;
                    break;
                }
            }
        }

        return ip;
    }

    /**
     * 判断字符串是否为有效IP
     */
    private static boolean isValidIp(String ip) {
        return ip != null && !ip.trim().isEmpty() && !"unknown".equalsIgnoreCase(ip);
        // 可以添加正则表达式进一步验证IP格式，例如 IPv4/IPv6
    }
}
